from rest_framework import serializers
from django_redis import get_redis_connection


class SmsCodeSerializer(serializers.Serializer):
    text = serializers.CharField(max_length=4,min_length=4,label="圖片驗證碼")
    image_code_id = serializers.UUIDField(label="驗證碼編碼")

    def validate(self, attrs):
        # 獲取text,image_code_id
        text = attrs["text"]
        image_code_id = attrs["image_code_id"]

        # 取出redis中的驗證碼
        redis_conn = get_redis_connection("code")
        redis_text = redis_conn.get("image_code_%s"%image_code_id)

        # 判斷是否過期
        if not redis_text:
            raise serializers.ValidationError("驗證碼已過期")

        # 刪除驗證碼
        redis_conn.delete("image_code_%s"%image_code_id)

        # 判斷正確性
        if text.upper() != redis_text.decode().upper():
            raise serializers.ValidationError("驗證碼錯誤")

        # 返回
        return attrs